//
//  NSObject+MDHNSObject.m
//  MDHPT
//
//  Created by 高得华 on 2019/4/24.
//  Copyright © 2019年 高得华. All rights reserved.
//

#import "NSObject+MDHNSObject.h"
#if __has_include(<MJExtension/MJExtension.h>)
#import <MJExtension/MJExtension.h>
#else
#import "MJExtension.h"
#endif
#import <objc/runtime.h>
#import "MDHMacroHeader.h"

@implementation NSObject (MDHNSObject)

///Hook进行修改 字体的大小
+ (void)load {
    ///字体方面
    ///系统
    Method fontSysOld = class_getClassMethod(UIFont.class, @selector(systemFontOfSize:));
    Method fontSysNew = class_getClassMethod(self, @selector(hook_systemFontOfSize:));
    method_exchangeImplementations(fontSysOld, fontSysNew);
    ///名字
    Method fontNameOld = class_getClassMethod(UIFont.class, @selector(fontWithName:size:));
    Method fontNameNew = class_getClassMethod(self, @selector(hook_fontWithName:size:));
    method_exchangeImplementations(fontNameOld, fontNameNew);
    ///italicSystem
    Method fontItalicOld = class_getClassMethod(UIFont.class, @selector(italicSystemFontOfSize:));
    Method fontItalicNew = class_getClassMethod(self, @selector(hook_italicSystemFontOfSize:));
    method_exchangeImplementations(fontItalicOld, fontItalicNew);
    ///BoldSystem
    Method fontBoldSystemOld = class_getClassMethod(UIFont.class, @selector(boldSystemFontOfSize:));
    Method fontBoldSystemNew = class_getClassMethod(self, @selector(hook_boldSystemFontOfSize:));
    method_exchangeImplementations(fontBoldSystemOld, fontBoldSystemNew);
}


///Hook进行修改 字体的大小
///系统的
+ (UIFont *)hook_systemFontOfSize:(CGFloat)fontSize {
    return [UIFont hook_systemFontOfSize:fontSize*kMDHPTAutoScale()];
}
+ (UIFont *)hook_fontWithName:(NSString *)fontName size:(CGFloat)fontSize {
    return [UIFont hook_fontWithName:fontName size:fontSize*kMDHPTAutoScale()];
}
+ (UIFont *)hook_italicSystemFontOfSize:(CGFloat)fontSize {
    return [UIFont hook_italicSystemFontOfSize:fontSize*kMDHPTAutoScale()];
}
+ (UIFont *)hook_boldSystemFontOfSize:(CGFloat)fontSize {
    return [UIFont hook_boldSystemFontOfSize:fontSize*kMDHPTAutoScale()];
}


//MARK: - ===== MHExtension 👇👇👇👇👇👇
+ (NSInteger) mh_randomNumberWithFrom:(NSInteger)from to:(NSInteger)to{
    return (NSInteger)(from + (arc4random() % (to - from + 1)));
}

- (void)mh_convertNotification:(NSNotification *)notification completion:(void (^ _Nullable)(CGFloat, UIViewAnimationOptions, CGFloat))completion
{
    // 按钮
    NSDictionary *userInfo = notification.userInfo;
    // 最终尺寸
    CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 开始尺寸
    CGRect beginFrame = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    // 动画时间
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    /// options
    UIViewAnimationOptions options = ([userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue] << 16 ) | UIViewAnimationOptionBeginFromCurrentState;
    
    /// keyboard height
    CGFloat keyboardH = 0;
    if (beginFrame.origin.y == [[UIScreen mainScreen] bounds].size.height){
        // up
        keyboardH = endFrame.size.height;
    }else if (endFrame.origin.y == [[UIScreen mainScreen] bounds].size.height) {
        // down
        keyboardH = 0;
    }else{
        // up
        keyboardH = endFrame.size.height;
    }
    /// 回调
    !completion?:completion(duration,options,keyboardH);
}



/// Get class
- (BOOL)mh_isStringClass { return [self isKindOfClass:[NSString class]]; }
- (BOOL)mh_isNumberClass { return [self isKindOfClass:[NSNumber class]]; }
- (BOOL)mh_isArrayClass { return [self isKindOfClass:[NSArray class]]; }
- (BOOL)mh_isDictionaryClass { return [self isKindOfClass:[NSDictionary class]]; }
- (BOOL)mh_isStringOrNumberClass { return [self mh_isStringClass] || [self mh_isNumberClass]; }
- (BOOL)mh_isNullOrNil { return !self || [self isKindOfClass:[NSNull class]]; }
- (BOOL)mh_isExist {
    if (self.mh_isNullOrNil) return NO;
    if (self.mh_isStringClass) return (self.mh_stringValueExtension.length>0);
    return YES;
}

/// Get value
- (NSString *)mh_stringValueExtension{
    if ([self mh_isStringClass]) return [(NSString *)self length]? (NSString *)self: @"";
    if ([self mh_isNumberClass]) return [NSString stringWithFormat:@"%@", self];
    return @"";
}


+ (id)loadInfo:(Class)aclass withKey:(NSString *)key
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *loginInfo = [ud objectForKey:key];
    if (loginInfo)
    {
        id ret = [[aclass class] mj_objectWithKeyValues:loginInfo];
        if (ret)
        {
            return ret;
        }
        else
        {
            return loginInfo;
        }
    }
    return @"";
}


+ (void)saveInfo:(NSObject *)obj withKey:(NSString *)key
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    if (obj)
    {
        if ([obj isKindOfClass:[NSString class]])
        {
            [ud setObject:obj forKey:key];
        }
        else
        {
            NSDictionary *dic = [obj mj_JSONObject];
            
            if ([NSJSONSerialization isValidJSONObject:dic])
            {
                NSError *error = nil;
                NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
                if(error)
                {
                    DTLog(@"存储失败");
                }
                NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                [ud setObject:str forKey:key];
            }
        }
        
        [ud synchronize];
    }
    else
    {
        [ud removeObjectForKey:key];
    }
}
//MARK: - ===== MHExtension 👆👆👆👆👆👆


@end






@implementation NSObject (CommonBlock)

- (void)excuteBlock:(CommonBlock)block
{
    __weak id selfPtr = self;
    if (block) {
        block(selfPtr);
    }
}

- (void)performBlock:(CommonBlock)block
{
    if (block)
    {
        [self performSelector:@selector(excuteBlock:) withObject:block];
    }
}

- (void)performBlock:(CommonBlock)block afterDelay:(NSTimeInterval)delay
{
    if (block)
    {
        [self performSelector:@selector(excuteBlock:) withObject:block afterDelay:delay];
    }
}

- (void)cancelPerformBlock:(CommonBlock)block {
    if (block) {
        [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(excuteBlock:) object:block];
        //[self cancelPreviousPerformRequestsWithTarget:self selector:@selector(excuteBlock:) object:block];
    }
}

- (void)cancelBlock:(CommonBlock)block
{
    [[NSRunLoop currentRunLoop] cancelPerformSelector:@selector(excuteBlock:) target:self argument:block];
}


- (void)excuteCompletion:(CommonCompletionBlock)block withFinished:(NSNumber *)finished
{
    __weak id selfPtr = self;
    if (block) {
        block(selfPtr, finished.boolValue);
    }
}

- (void)performCompletion:(CommonCompletionBlock)block withFinished:(BOOL)finished
{
    if (block)
    {
        [self performSelector:@selector(excuteCompletion:withFinished:) withObject:block withObject:[NSNumber numberWithBool:finished]];
    }
}

- (void)cancelCompletion:(CommonCompletionBlock)block
{
    [[NSRunLoop currentRunLoop] cancelPerformSelector:@selector(excuteCompletion:withFinished:) target:self argument:block];
}

//- (void)performCompletion:(CommonCompletionBlock)block withFinished:(BOOL)finished afterDelay:(NSTimeInterval)delay
//{
//    if (block)
//    {
//        self performSelector:<#(SEL)#> withObject:<#(id)#> afterDelay:<#(NSTimeInterval)#>
////        [self performSelector:@selector(excuteCompletion:withFinished:) withObject:block withObject:[NSNumber numberWithBool:finished] afterDelay:delay];
//    }
//}

- (void)asynExecuteCompletion:(CommonBlock)completion tasks:(CommonBlock)task, ... NS_REQUIRES_NIL_TERMINATION
{
    va_list arguments;
    
    if (task)
    {
        if (task)
        {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                if (task)
                {
                    task(self);
                }
            });
            
            va_start(arguments, task);
            DTLog(@"%@ <<<<<<<<<=============", task);
            BOOL next = YES;
            do
            {
                CommonBlock eachObject = va_arg(arguments, CommonBlock);
                DTLog(@"%@ <<<<<<<<<=============", eachObject);
                if (eachObject)
                {
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        if (eachObject)
                        {
                            eachObject(self);
                        }
                    });
                }
                else
                {
                    next = NO;
                }
                
            }while (next);
            va_end(arguments);
        }
        
        
        
        
        dispatch_barrier_async(dispatch_get_global_queue(0, 0), ^{
            if (completion)
            {
                completion(self);
            }
        });
    }
}
@end






//MARK: - ===== UIViewController
@implementation UIViewController (MDHUIViewController)
@end


//MARK: - ===== UIScrollView
@implementation UIScrollView (MDHUIScrollView)
/// 添加下拉刷新控件
- (MJRefreshStateHeader *)mh_addHeaderRefresh:(void(^)(MJRefreshStateHeader *header))refreshingBlock {
    @weakify(self);
    MJRefreshGifHeader *mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        @strongify(self);
        !refreshingBlock?:refreshingBlock((MJRefreshStateHeader *)self.mj_header);
    }];
    mj_header.lastUpdatedTimeLabel.hidden = true;
    // Configure normal mj_header
    self.mj_header = mj_header;
    mj_header.stateLabel.hidden = true;
    // 设置正在刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=4; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"refresh_%zd", i]];
        if (image) {
            [refreshingImages addObject:image];
        }
    }
    [mj_header setImages:refreshingImages forState: MJRefreshStateRefreshing];
    [mj_header setImages:refreshingImages forState: MJRefreshStateIdle];
    [mj_header setImages:refreshingImages forState: MJRefreshStatePulling];
    return mj_header;
}

/// 添加上拉加载控件
- (MJRefreshAutoStateFooter *)mh_addFooterRefresh:(void(^)(MJRefreshAutoStateFooter *footer))refreshingBlock {
    @weakify(self);
    MJRefreshAutoNormalFooter *mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self);
        !refreshingBlock?:refreshingBlock((MJRefreshAutoStateFooter *)self.mj_footer);
    }];
    // Configure normal mj_footer
    [mj_footer setTitle:@"别拉了，已经到底了..." forState:MJRefreshStateNoMoreData];
    self.mj_footer = mj_footer;
    
    /*
     mj_footer.refreshingTitleHidden = true;
     // 设置正在刷新状态的动画图片
     NSMutableArray *refreshingImages = [NSMutableArray array];
     for (NSUInteger i = 1; i<=4; i++) {
     UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"refresh_%zd", i]];
     if (image) {
     [refreshingImages addObject:image];
     }
     }
     [mj_footer setImages:refreshingImages forState: MJRefreshStateRefreshing];
     [mj_footer setImages:refreshingImages forState: MJRefreshStateIdle];
     [mj_footer setImages:refreshingImages forState: MJRefreshStatePulling];
     */
    
    return mj_footer;
}
@end




@implementation UIColor (MDHColor)


+ (UIColor *)colorWithHexStr:(NSString *)color alpha:(CGFloat)alpha {
    //删除字符串中的空格
    NSString *cString = [[color
                          stringByTrimmingCharactersInSet:[NSCharacterSet
                                                           whitespaceAndNewlineCharacterSet]]
                         uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    // strip 0X if it appears
    //如果是0x开头的，那么截取字符串，字符串从索引为2的位置开始，一直到末尾
    if ([cString hasPrefix:@"0X"]) {
        cString = [cString substringFromIndex:2];
    }
    //如果是#开头的，那么截取字符串，字符串从索引为1的位置开始，一直到末尾
    if ([cString hasPrefix:@"#"]) {
        cString = [cString substringFromIndex:1];
    }
    if ([cString length] != 6) {
        return [UIColor clearColor];
    }
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    // r
    NSString *rString = [cString substringWithRange:range];
    // g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    // b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float)r / 255.0f)
                           green:((float)g / 255.0f)
                            blue:((float)b / 255.0f)
                           alpha:alpha];
}



@end
